package com.ctg.behavior.client.impala.utils;

import org.apache.commons.lang3.StringUtils;

public class CtCalcSQLDateUtils {

	public static String sqlDate2NumDate(String sql) {

		StringBuilder sbuf = new StringBuilder(sql);
		
		int index = sbuf.indexOf("WHERE");
		if (index < 0) {
			index = sbuf.indexOf("where");
		}
		if (index <= 0) {
			return sql;
		}
		
		for(int edi = 0 ; edi<2; edi ++) {
			// 处理from date & to date
			index = sbuf.indexOf("event_date", index+1);
			if (index < 0) {
				index = sbuf.indexOf("EVENT_DATE", index+1);
			}
			if (index <= 0) {
				return sql;
			}
			index = sbuf.indexOf("'", index);
			if (index <= 0) {
				return sql;
			}
			int endIndex = sbuf.indexOf("'", index + 1);
			if (endIndex <= 0) {
				return sql;
			}
			String dateStr = sbuf.substring(index+1, endIndex);
			dateStr = toNumDate(dateStr);
			sbuf = sbuf.replace(index+1, endIndex, dateStr);
		}

		return sbuf.toString();
	}

	public static String toNumDate(String stdDate) {
		return stdDate.replaceAll("-", "");
	}

	public static String toStdDate(String numDate) {
		if (StringUtils.isEmpty(numDate) || numDate.trim().length() != 8) {
			return numDate.trim();
		}
		numDate = numDate.trim();
		StringBuilder sbuf = new StringBuilder();
		sbuf.append(numDate.substring(0, 4));
		sbuf.append("-");
		sbuf.append(numDate.substring(4, 6));
		sbuf.append("-");
		sbuf.append(numDate.substring(6, 8));
		return sbuf.toString();
	}

}
